package net.easyjava.framework.web.elastiesearch;

import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.AdminClient;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.IndicesAdminClient;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutionException;

/**
 * Created by wenxiaoning on 16/6/19.
 */
@Deprecated
public class Main {
    public static void main(String[] args) {
        Settings settings = Settings.settingsBuilder()
                .put("cluster.name", "cluster_wxnacy")
                .put("client.transport.sniff", true).build();
        Client client = null;
        try {
            client = TransportClient.builder().settings(settings).build()
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
//        Client client = null;
//        try {
//            client = TransportClient.builder().build()
//                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9200))
//                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9200));
//        } catch (UnknownHostException e) {
//            e.printStackTrace();
//        }

//        Settings settings = Settings.settingsBuilder()
//                .put("client.transport.sniff", true)
//                .put("client.transport.ignore_cluster_name",true).build();
//        TransportClient client = TransportClient.builder().settings(settings).build();
// on shutdown


        String json = "{" +
                "\"user\":\"kimchy trying\"," +
                "\"postDate\":\"2013-01-30\"," +
                "\"message\":\"trying out Elasticsearch\"" +
                "}";

        //创建索引
        IndexResponse response = client.prepareIndex("twitter", "tweet")
                .setSource(json)
                .get();

        System.out.println("response.getIndex() = " + response.getIndex());
        System.out.println("response.getId() = " + response.getId());
        System.out.println("response.getType() = " + response.getType());
        System.out.println("response = " + response.isCreated());

        //读取索引
        GetResponse getResponse = client.prepareGet("twitter", "tweet", "AVVfH2L_QhKOdu7hko2F")
//                .setOperationThreaded(false)
                .get();
        System.out.println("getResponse() = " + getResponse);
        System.out.println("getResponse.getIndex() = " + getResponse.getIndex());
        System.out.println("getResponse.getId() = " + getResponse.getId());
        System.out.println("getResponse.getSource() = " + getResponse.getSource());
        System.out.println("getResponse.getSourceAsString() = " + getResponse.getSourceAsString());

        System.out.println("MultiGetResponse=====================================");
        //多重获取
        MultiGetResponse multiGetItemResponses = client.prepareMultiGet()
                .add("twitter", "tweet", "AVViS6ckQhKOdu7hkrRc")
                .add("twitter", "tweet", "AVViT3XfQhKOdu7hkrWj", "3", "4")
                .add("another", "type", "foo")
                .get();

//        for (MultiGetItemResponse itemResponse : multiGetItemResponses) {
//            GetResponse getResponse1 = itemResponse.getResponse();
//            System.out.println("getResponse1.isExists() = " + getResponse1.isExists());
//            if (getResponse1.isExists()) {
//                System.out.println("getResponse1.isSourceEmpty() = " + getResponse1.isSourceEmpty());
//            }
//        }


        //删除
        DeleteResponse deleteResponse = client.prepareDelete("twitter", "tweet", "1")
//                .setOperationThreaded(false)
                .get();
        System.out.println("Main.main===================================");
        System.out.println("deleteResponse.getIndex() = " + deleteResponse.getIndex());
        System.out.println("deleteResponse.getId() = " + deleteResponse.getId());
        System.out.println("deleteResponse.isFound() = " + deleteResponse.isFound());

        //修改
        UpdateRequest updateRequest = new UpdateRequest();
        updateRequest.index("twitter");
        updateRequest.type("tweet");
        updateRequest.id("AVVfG66bQhKOdu7hkoxV");
        updateRequest.doc(json);
        try {
            client.update(updateRequest).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        System.out.println("批量操作====================");

        //批量操作
        BulkRequestBuilder bulkRequest = client.prepareBulk();

// either use client#prepare, or use Requests# to directly build index/delete requests
        bulkRequest.add(client.prepareIndex("index_1", "tweet", "1")
                        .setSource(json
                        )
        );

        bulkRequest.add(client.prepareIndex("index_2", "tweet", "2")
                        .setSource(json
                        )
        );bulkRequest.add(client.prepareDelete("index_2", "tweet", "2")

        );

        BulkResponse bulkResponse = bulkRequest.get();
        System.out.println("bulkResponse.hasFailures() = " + bulkResponse.hasFailures());
        if (bulkResponse.hasFailures()) {
            // process failures by iterating through each bulk response item
        }

//        BulkProcessor bulkProcessor = BulkProcessor.builder(
//                client,
//                new BulkProcessor.Listener() {
//                    @Override
//                    public void beforeBulk(long executionId,
//                                           BulkRequest request) {
//                        System.out.println("Main.beforeBulk");
//                    }
//
//                    @Override
//                    public void afterBulk(long executionId,
//                                          BulkRequest request,
//                                          BulkResponse response) {
//                        System.out.println("Main.afterBulk");
//                    }
//
//                    @Override
//                    public void afterBulk(long executionId,
//                                          BulkRequest request,
//                                          Throwable failure) {
//                        System.out.println("Main.afterBulk");
//                    }
//                })
//                .setBulkActions(10000)
//                .setBulkSize(new ByteSizeValue(1, ByteSizeUnit.GB))
//                .setFlushInterval(TimeValue.timeValueSeconds(5))
//                .setConcurrentRequests(1)
//                .setBackoffPolicy(
//                        BackoffPolicy.exponentialBackoff(TimeValue.timeValueMillis(100), 3))
//                .build();
//
//        bulkProcessor.close();



        //搜索
        long begin = System.currentTimeMillis();
        SearchResponse searchResponse = client.prepareSearch("twitter")
                .setTypes("tweet")
                .setSize(20)
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(QueryBuilders.queryStringQuery("trying"))                 // Query
//                .setPostFilter(QueryBuilders.rangeQuery("age").from(12).to(18))     // Filter
//                .setFrom(0).setSize(60).setExplain(true)
                .execute()
                .actionGet();
        System.out.println("Main.main=============================");

        System.out.println("searchResponse.getHits().getTotalHits() = " + searchResponse.getHits().getTotalHits());
        System.out.println("searchResponse.getTook() = " + searchResponse.getTook());
        for(SearchHit searchHit:searchResponse.getHits().getHits()){
//            System.out.println("searchHit.getId() = " + searchHit.getId());
//            System.out.println("searchHit.getSourceAsString() = " + searchHit.getSourceAsString());
        }
        long end = System.currentTimeMillis();
        System.out.println("(end-begin) = " + (end - begin));



        //多重搜索
//        SearchRequestBuilder srb1 = node.client()
//                .prepareSearch().setQuery(QueryBuilders.queryStringQuery("elasticsearch")).setSize(1);
//        SearchRequestBuilder srb2 = node.client()
//                .prepareSearch().setQuery(QueryBuilders.matchQuery("name", "kimchy")).setSize(1);
//
//        MultiSearchResponse sr = node.client().prepareMultiSearch()
//                .add(srb1)
//                .add(srb2)
//                .execute().actionGet();
//
//// You will get all individual responses from MultiSearchResponse#getResponses()
//        long nbHits = 0;
//        for (MultiSearchResponse.Item item : sr.getResponses()) {
//            SearchResponse response = item.getResponse();
//            nbHits += response.getHits().getTotalHits();
//        }

        //查询数量
//        CountResponse countResponse = client.prepareCount("test")
//                .setQuery(termQuery("_type", "type1"))
//                .execute()
//                .actionGet();

        //管理员
        AdminClient adminClient = client.admin();
        IndicesAdminClient indicesAdminClient = client.admin().indices();
//        indicesAdminClient.analyze();

        client.close();
    }
}
